const express = require('express');
const cors = require('cors');
const rateLimit = require('express-rate-limit');
const compression = require('compression');
const { config } = require('./config/db');
const app = express();
const { pool } = require('./config/db');
const cron = require('node-cron');

// 添加定时任务：每日零点重置visit_count，并更新yesterday_visit字段
cron.schedule('0 0 * * *', async () => {
  try {
    await pool.query('UPDATE system_status SET yesterday_visit = visit_count, visit_count = 0 WHERE id = 1');
    console.log('Visit count reset to 0 successfully, yesterday_visit updated');
  } catch (error) {
    console.error('Error resetting visit count:', error);
  }
});

const redirectRoutes = require('./routes/redirectRoutes');
const resourcesRoutes = require('./routes/resourcesRoutes');
const groupsRoutes = require('./routes/groupsRoutes');
const targetsRoutes = require('./routes/targetsRoutes');
const systemRoutes = require('./routes/systemRoutes');

// 启用CORS，允许所有来源
app.use(cors());

// 启用请求体解析
app.use(express.json());

// 配置速率限制
const limiter = rateLimit({
    windowMs: config.RATE_LIMIT.WINDOW_MS,
    max: config.RATE_LIMIT.MAX_REQUESTS,
    message: '请求过于频繁，请稍后再试'
});

// 应用速率限制到所有请求
app.use(limiter);

// 启用压缩
if (config.PERFORMANCE.COMPRESSION) {
    app.use(compression());
}

app.use('/r', redirectRoutes);
app.use('/api/resources', resourcesRoutes);
app.use('/api/groups', groupsRoutes);
app.use('/api/targets', targetsRoutes);
app.use('/api/system', systemRoutes);

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});